package com.heitian.ssm.utils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: mishuai
 * Date: 2018-04-19
 * Time: 13:13
 * Des:
 */
public class SendEmail {

    private final static String FROM_EMAIL = "yangzinan127@163.com";
    private final static String HOST = "smtp.163.com";
    private final static String PASSWORD = "mimi1996";
    private final static String SMTP = "smtp";
    private static Properties properties = new Properties();
    private static Session session;

    public static void sendMail(String to, String title, String context) throws Exception {

        properties.setProperty("mail.transport.protocol", "smtp");//电子邮箱协议

        properties.setProperty("mail.smtp.host", HOST); //邮箱服务器地址

        properties.setProperty("mail.smtp.auth", "true");

        session = Session.getInstance(properties);

        session.setDebug(true);//开启调试模式，可以追踪到邮件发送过程

        MimeMessage mimeMessage = new MimeMessage(session);

        mimeMessage.setSubject(title);//标题

        mimeMessage.setContent(context, "text/html;charset=utf-8");//内容

        mimeMessage.setFrom(new InternetAddress(FROM_EMAIL));//发送人

        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人

        mimeMessage.setSentDate(new Date());//发送时间

        mimeMessage.saveChanges();//保存修改

        Transport transport = session.getTransport(SMTP);

        transport.connect(FROM_EMAIL, PASSWORD);

        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

        transport.close();

    }
}